sugarfreeControllers.controller('ProfileController', ['$scope','$log','$q','$http', '$filter','$route','$timeout','Utils','DictionarySerivce','UploadService','ProfileService','QINIU',function($scope,$log,$q,$http,$filter,$route,$timeout,Utils,dicService,uploadService,profileService,QINIU) {
  "use strict";
  
  $scope.text = "hello chengwan";

  $scope.unEditForm = function(){unEditForm();};
  
  $scope.reUnEditForm = function(){reUnEditForm();};
  
  $scope.updateProfile = function() {updateProfile();};
  
  $scope.removeProfileImg = function(index, cert_id) {removeProfileImg(index,cert_id);};
  
  $scope.changed = function(){changed();};
  
  $scope.getShiQuXian =  function(shengshi){ getShiQuXian(); };
  
  $scope.getShangQuan = function(shengshi,shiquxian){getShangQuan(); };
  
  $scope.delProfileImage = function(fileId){delProfileImage(fileId);};
  
  $scope.delOriginProfileImg = function(index,fileId){delOriginProfileImg(index,fileId)};
  
  
  ///////////////
  
  
  function unEditForm(){
	  if(!modifyFlag){
      //temporary keep
      //$scope.profile = angular.copy(originalProfile);
      $scope.profileEditImages = [];
		  $scope.page.useEdit = false;
      $scope.errMsg={};
	  }else{
		  Utils.setParclose(true);
		  $scope.page.useOffEditConfirm = true;
	  }
  }
  
  function reUnEditForm(){ 
	  $scope.profile = angular.copy(originalProfile);
	  $scope.profileEditImages = [];
    $scope.errMsg = {};
	  $scope.page.useOffEditConfirm = false;
	  Utils.setParclose(false);
	  $scope.page.useEdit = false;
	  modifyFlag = false;
  }
  

  function updateProfile(){
      var checkeResult = profileService.checkField($scope.profile,$scope.msg);
      $scope.errMsg = checkeResult.errMsg;
    	if(checkeResult.valid){
    		$scope.form.submitted = false;
    		var deviceSum = 0;
  			angular.forEach($scope.deviceCheckeboxs,function(device){
  				if(device.checked){
  					deviceSum += device.value;
  				}
  			});
        $scope.profile.deviceSum = deviceSum;

        Utils.setProcessParclose(true);
  			profileService.updateProfile($scope.profile,$scope.profileEditImages)
        .then(function(rsps){
          //uploadImage();
          alert("场馆信息修改成功");
          $scope.page.useEdit = false;
          Utils.setProcessParclose(false);
          if($scope.log.debug){
            console.log('update profile success',rsps);
          }
          $route.reload();
        },function(rsps){
          alert("场馆信息修改失败");
          Utils.setProcessParclose(false);
          if($scope.log.debug){
            console.error('update profile failed',rsps);
          }
        });

    	}else{
          $scope.form.submitted = true;
      }
  }
  
  
  $scope.changeContact = function(){
	  var found = $filter('filter')($scope.coachs, {id: $scope.profile.contactId}, true);
	  if(found.length){
		  $scope.profile.contactMobile = found[0].mobile;
	  }else{
		  console.log("profile.contactMobile",$scope.profile.contactMobile);
		  $scope.profile.contactMobile = "";
	  }
  };
  
  
  
  // make sure start time is 1hr earlier than endtime
  function changed() {
    var  _elapseT= $scope.profile.tcloseTime.getTime() - $scope.profile.topenTime.getTime();
    console.log("time changed:", _elapseT, $scope.profile.tcloseTime, $scope.profile.topenTime);
    if (_elapseT < 60*60*1000) {
      $scope.profile.tcloseTime = new Date($scope.profile.topenTime.getTime() + $scope.profile.mstep * 2 * 60 * 1000);

    }
  }
  

  function removeProfileImg(index, imgId) {
    profileService.removeProfileImg(imgId)
    .then(function(rsps){
      $scope.profile.images.splice(index, 1);
    },function(rsps){
      alert("图片删除失败");
    });
	}
  
  
  
  //保存提交上传
 function uploadImage(){
    profileService.getImageUpToken()
      .then(function(rsps){
        $scope.uploader.setOption("uptoken",rsps.data.uptoken);
        $scope.uploader.start();
      },function(rsps){
        $log.error("获取上传图片令牌失败！",rsps);
      });
 }
  


  //删除一张图片
  $scope.delImage=function(fileid){
    uploadService.delImage($scope,fileid);
  };
  
  //upimage end...
  function  getShiQuXian(){
	  dicService.getShiQuXian($scope.profile.region.shengShi).success(function(data){
		  $scope.shiquxians = data;
		  if($scope.log.debug){
			  $log.info("$scope.shiquxians",$scope.shiquxians);
		  }
	  });
  }
  
  function getShangQuan(){
	  dicService.getShangQuan($scope.profile.region.shengShi,$scope.profile.region.shiQuXian).success(function(data){
	  	if(data.length > 0){
	  		$scope.shangquans = data[0].shangQuanArray;
	  	}else{
	  		$scope.shangquans = [];
	  	}
		  if($scope.log.debug){
			  $log.info("$scope.shangquans",data,$scope.shangquans);
		  }
	  });
  }
  
  function delProfileImage(fileId){
  	$scope.profileEditImages = removeElementInArray($scope.profileEditImages,fileId);
  }
  
  function removeElementInArray(array,fileId){
    	console.info("fileId:",array.length);
    	var _array = [];
    	for(var i = 0; i< array.length ; i++){
    		console.info(i+":",array[i]);
    		if(array[i]['id'] !== fileId){
    			_array.push(array[i]);
    		}
    	}
    	return _array;
  }
  
  function delOriginProfileImg(index,fileId){
  	$scope.profile.images.splice(index, 1);
    $scope.profile.deletedImages = $scope.profile.deletedImages || [];
    $scope.profile.deletedImages.push(fileId);
  }
  
  
  //ProfileController initData()
  var originalProfile;
  var modifyFlag=false;
  function initData() {
	$scope.page = {
		useEdit:false,
		useOffEditConfirm:false
	};  
    $scope.log={
    		debug:true
    };
	$scope.msg={
			emptyRegion:"错误：请选择场馆所在区域",
			emptyContact:"错误：请选择主负责人",
	};
	$scope.errMsg = {};
    $scope.logoUploader = {};
    
    
    Utils.setProcessParclose(true);
    $q.all([
     profileService.retrieveProfile("profile/get"),
	   dicService.getShengShi(),
	   dicService.getCoachs(),
	   dicService.queryDevice()
    ])
    .then(function(results){
    	var profile 	= results[0].data;
    	var shengshis = results[1].data;
    	var coachs 		= results[2].data;
    	var devices 	= results[3].data;
    	
    	var deviceCheckeboxs =[];
    	angular.forEach(devices,function(device){
    		var element = {
    				name:device.name,
    				value:device.value,
    				thumbnail:device.thumbnail,
    				checked:false
    		};
    		deviceCheckeboxs.push(element);
    	});
    	
    	$scope.shengshis = shengshis;
    	$scope.coachs = coachs;
    	$scope.deviceCheckeboxs = deviceCheckeboxs;
    	$scope.profile = profileService.generateProfile(profile,shengshis,coachs,$scope.deviceCheckeboxs,devices);
    	originalProfile = angular.copy($scope.profile);
    	//watch
    	var watch = $scope.$watchCollection('profile',function(newValue,oldValue){
        //console.log("newValue",newValue);
        //console.log("originalProfile",originalProfile);

    		if(!angular.equals(newValue,originalProfile)){
    			modifyFlag = true;
    		}
    	});
    	Utils.setProcessParclose(false);
    	if(profile.region){
    		$q.all([
		        dicService.getShiQuXian(profile.region.shengShi),
		        dicService.getShangQuan(profile.region.shengShi,profile.region.shiQuXian)
    		])
    		.then(function(results){
    			$scope.shiquxians = results[0].data;
    			$scope.shangquans = results[1].data[0].shangQuanArray;
    		});
    	}
    });

		$scope.qiniuDomain = QINIU.domain;
		$scope.logoImage = [];
		$scope.profileEditImages = [];
//upimage start chengwanliu...
//  $timeout(function() { 
//    $scope.uploader = uploadService.createuploader("token","pickfiles");
//  }, 1);
    
    
    //logo upload
//    profileService.getLogoUpToken()
//      .then(function(rsps){
//        $scope.uploader_logo = uploadService.createuploader("token","pickfiles_logo",true);
//        $scope.uploader_logo.setOption("uptoken",rsps.data.uptoken);
//        $scope.logoUptoken = rsps.data.uptoken;
//      },function(rsps){
//        $log.error("获取上传Logo令牌失败！",rsps);
//      });
  }
  initData();
}]);